package com.xuzhijie.pms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuzhijie.pms.common.Constants;
import com.xuzhijie.pms.common.Result;
import com.xuzhijie.pms.entity.*;
import com.xuzhijie.pms.entity.dto.OwnerDto;
import com.xuzhijie.pms.entity.vo.NoticeVo;
import com.xuzhijie.pms.entity.vo.PetVo;
import com.xuzhijie.pms.entity.vo.PropertyVo;
import com.xuzhijie.pms.exception.PmsServerException;
import com.xuzhijie.pms.mapper.OwnerMapper;
import com.xuzhijie.pms.mapper.PetMapper;
import com.xuzhijie.pms.mapper.PropertyMapper;
import com.xuzhijie.pms.mapper.VehicleMapper;
import com.xuzhijie.pms.service.IOwnerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuzhijie.pms.utils.JwtUtils;
import com.xuzhijie.pms.utils.saltUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 许志杰
 * @since 2024-02-16
 */
@Service
public class OwnerServiceImpl extends ServiceImpl<OwnerMapper, Owner> implements IOwnerService {

    @Resource
    private PropertyMapper propertyMapper;

    @Resource
    private VehicleMapper vehicleMapper;

    @Resource
    private PetMapper petMapper;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.req-dir}")
    private String reqDir;

    @Value("${server.port}")
    private String port;

    @Value("${file.ip}")
    private String ip;

    @Override
    public Result findPage(Integer page, Integer size, Integer isRefine, Date startTime, Date endTime, String phone) {
        Page<Owner> ownerPage = new Page<>(page,size);
        QueryWrapper<Owner> queryWrapper = new QueryWrapper<>();
        Page<Owner> result;
        Long total;
        if (startTime != null && endTime != null){
            queryWrapper.between("create_time",startTime,endTime);
        }
        if (!isRefine.equals(0)){
            queryWrapper.eq("is_refine",isRefine);
        }
        if (StrUtil.isNotBlank(phone)){
            queryWrapper.like("phone",phone);
        }

        try {
            result = page(ownerPage,queryWrapper);
            total = count(queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            throw new PmsServerException("业务繁忙", Constants.SYSTEM_ERROR);
        }
        List<Owner> records = result.getRecords();

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("records",records);
        resultMap.put("total",total);
        return Result.success(resultMap);

    }

    @Override
    public Result getOwnerInfo(String ownerId) {
        System.out.println("ownerId: "+ownerId);
        Owner owner = getById(ownerId);
        QueryWrapper<Property> propertyQueryWrapper = new QueryWrapper<>();
        propertyQueryWrapper.eq("owner",ownerId);
        List<Property> list = propertyMapper.selectList(propertyQueryWrapper);
        List<PropertyVo> voList = new ArrayList<>();
        for (Property property : list) {
            PropertyVo vo = new PropertyVo(property);
            BeanUtil.copyProperties(property,vo);
            voList.add(vo);
        }

        QueryWrapper<Vehicle> vehicleQueryWrapper = new QueryWrapper<>();
        vehicleQueryWrapper.eq("master",ownerId);
        List<Vehicle> vehicleList = vehicleMapper.selectList(vehicleQueryWrapper);

        QueryWrapper<Pet> petQueryWrapper = new QueryWrapper<>();
        petQueryWrapper.eq("master",ownerId);
        List<Pet> petList = petMapper.selectList(petQueryWrapper);
        List<PetVo> petVoList = new ArrayList<>();
        for (Pet pet : petList) {
            PetVo petvo = new PetVo(pet);
            BeanUtil.copyProperties(pet,petvo);
            petVoList.add(petvo);
        }

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("owner",owner);
        resultMap.put("propertyList",voList);
        resultMap.put("vehicleList",vehicleList);
        resultMap.put("petList",petVoList);

        System.out.println(resultMap);

        return Result.success(resultMap);
    }



    @Override
    public Result unbindingProperty(String id) {
        if (StrUtil.isBlank(id)){
            return Result.error();
        }



        Property property = propertyMapper.selectById(id);
        property.setCheckIn(2);
        property.setCheckInTime(null);
        property.setOwner("0000000001");
        propertyMapper.updateById(property);

        return Result.success();
    }

    @Override
    public Result getOwnerByPhone(String phone) {
        QueryWrapper<Owner> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        System.out.println(phone);
        long count = count(queryWrapper);
        if (count >= 1){
            return Result.success();
        }

        return Result.error(Constants.ILLEGAL_PARAMETERS,"业主未创建");
    }

    @Override
    public Result ownerLogin(String phone, String password, String nickName, String face) {

        //1.判断是否存在用户
        if (StrUtil.isBlank(phone)&&StrUtil.isNotBlank(password)){
            return Result.error(Constants.ILLEGAL_PARAMETERS,"电话和密码不能为空");
        }

        QueryWrapper<Owner> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        Owner one = getOne(queryWrapper);

        if (BeanUtil.isNotEmpty(one)){
            String realPassword =saltUtil.encodePassword(password,one.getSalt());
            String dataPassword = one.getPassword();
            //用户存在，直接登录，返回token
            if (!(realPassword.equals(dataPassword) && nickName.equals(one.getNickName()))){
                return Result.error(Constants.ILLEGAL_PARAMETERS,"用户名或密码错误");
            }

//            if (!face.equals(one.getFace())){
//                String newFace = createNewFace(face);
//                one.setFace(newFace);
//            }

            OwnerDto ownerDto = new OwnerDto();
            BeanUtil.copyProperties(one,ownerDto);
            ownerDto.setToken(JwtUtils.generateToken(one.getId(),one.getSalt()));
            saveOrUpdate(one);
            return Result.success(ownerDto);
        }else{
            return Result.error(Constants.ILLEGAL_PARAMETERS,"用户不存在");
//            QueryWrapper<Owner> queryWrapper1 = new QueryWrapper<>();
//            queryWrapper1.eq("nick_name",nickName);
//            List<Owner> list = list(queryWrapper1);
//            if (list.size() == 0){
//                return Result.error(Constants.ILLEGAL_PARAMETERS,"用户名已存在");
//            }
//            Owner owner = createOwner(phone, password, nickName, face);
//            OwnerDto ownerDto = new OwnerDto();
//            BeanUtil.copyProperties(owner,ownerDto);
//
//            return Result.success(ownerDto);
        }
    }

    @Override
    public Result ownerregister(String phone, String password, String nickName, String face) {
        QueryWrapper<Owner> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("nick_name", nickName);
        List<Owner> list = list(queryWrapper1);
        System.out.println(nickName);
        for (Owner owner : list) {
            System.out.println(owner.getNickName());
        }
        if (list.size() != 0) {
            return Result.error(Constants.ILLEGAL_PARAMETERS, "用户名已存在");
        }

        List<Owner> list2 = list(new QueryWrapper<Owner>().eq("phone", phone));

        if (list2.size() != 0) {
            return Result.error(Constants.ILLEGAL_PARAMETERS, "号码被占用");
        }
//        String newFace = createNewFace(face);

        Owner owner = createOwner(phone, password, nickName, face);
        OwnerDto ownerDto = new OwnerDto();
        BeanUtil.copyProperties(owner,ownerDto);
        return Result.success(ownerDto);
    }


    public Owner createOwner(String phone, String password, String nickName, String face){



        Owner owner = new Owner();
        owner.setNickName(nickName);
        owner.setPhone(phone);
        owner.setSalt(saltUtil.generateSalt());
        owner.setFace(face);
        owner.setIsRefine(2);
        owner.setStatus(1);
        owner.setPassword(saltUtil.encodePassword(password,owner.getSalt()));
        save(owner);

        return owner;
    }

//    private String createNewFace(String face) {
//        String suffix = StrUtil.subAfter(face, ".", true);
//        String newFileName = UUID.randomUUID().toString() + "." + suffix;
//        String uploadDir = "F:\\pmsimage\\" +newFileName;
//
//        byte[] bytes = HttpUtil.downloadBytes(face);
//        FileUtil.writeBytes(bytes,uploadDir);
//        String fileUrl = ip + port + "/"+ reqDir +"/" + newFileName;
//        return fileUrl;
//    }

}
